#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>

#include "../utils/config.h"


// 测试用的回调函数
static void test_handler(void* user, const char* section, const char* key, char* value) {
    printf("[%s] , key:%s = value:%s\n", section, key, value);
}


// 创建临时INI文件用于测试
static int create_test_ini(const char* path) {
    FILE* f = fopen(path, "w");
    if (!f) return -1;
    
    fprintf(f, "# Test INI file\n");
    fprintf(f, "[database]\n");
    fprintf(f, "host = 127.0.0.1\n");
    fprintf(f, "port = 3306\n");
    fprintf(f, "  user   = root  \n");  // 测试空格处理
    fprintf(f, "\n");  // 空行
    fprintf(f, "[server]\n");
    fprintf(f, "listen=8080\n");  // 无空格
    fprintf(f, "timeout = 30\n");
    
    fclose(f);
    return 0;
}

int main(int argc, char* argv[]) {
    const char* test_file;
    
    // 创建测试文件
    if (argc<=1)
    {
        test_file = "test_config.ini";
        if (create_test_ini(test_file) != 0) {
            fprintf(stderr, "Failed to create test file\n");
            return 1;
        }
    }else
    {
        /* code */
        test_file = argv[1];
    }
    
    
    // 测试正常解析
    printf("=== Testing normal parsing ===\n");
    long mtime = 0;
    int ret = ini_mmap_parse(NULL, test_file, test_handler, &mtime);
    if (ret != 0) {
        printf("Parse failed with error: %d\n", ret);
    } else {
        printf("Parse succeeded. File mtime: %ld\n", mtime);
    }
    
    // 测试不存在的文件
    // printf("\n=== Testing non-existent file ===\n");
    // ret = ini_mmap_parse(NULL, "nonexistent.ini", test_handler, NULL);
    // printf("Return code: %d %s (expected -2)\n", ret,strerror(errno));
    
    // 测试空文件
    // printf("\n=== Testing empty file ===\n");
    // FILE* f = fopen("empty.ini", "w");
    // fclose(f);
    // ret = ini_mmap_parse(NULL, "empty.ini", test_handler, NULL);
    // printf("Return code: %d (expected 0)\n", ret);
    
    // 清理
    // unlink(test_file);
    // unlink("empty.ini");
    
    return 0;
}
// 编译命令: gcc -o testmmp testmmp.c config.c  -L../src -lmonexec -Wl,-rpath=../src
// 运行命令: ./testmmp